package java6699.nio2_New;

import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.stream.Stream;

/**
 * @program: java_zzx
 * @description:
 * @author: zzx
 * @create: 2022-10-19 16:42
 **/
public class NIO2Dir6699Controller {
    @FXML
    public TextField tfDir;
    @FXML
    public Label lblCount;
    @FXML
    public TableView<MyFile6699> tableFiles;
    @FXML
    public TableColumn<MyFile6699, String> colName;
    @FXML
    public TableColumn<MyFile6699, String> colTime;
    @FXML
    public TableColumn<MyFile6699, String> colType;
    @FXML
    public TableColumn<MyFile6699, String> colSize;
    private ObservableList<MyFile6699> list;
    private Path CuDir;
    private int nDir = 0, nFile = 0;
    @FXML
    private void initialize() {
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colType.setCellValueFactory(new PropertyValueFactory<>("type"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("modifiedTime"));
        colSize.setCellValueFactory(new PropertyValueFactory<>("size"));
        list = tableFiles.getItems();
    }
    @FXML
    public void listAll(ActionEvent actionEvent) throws IOException {
        String filename = tfDir.getText().trim();
        //如果输入为空，则显示当前目录
        if (filename.isEmpty()) {
            filename = ".";
        } else {
            //检查输入的目录是否正确（Files的isDirectory方法）
            if (!Files.isDirectory(Paths.get(filename))) {
                lblCount.setText("不是目录！");
            } else if (filename.matches("[a-zA-Z]:")) {
                filename += ".";
            }
        }
        setCuDir(Paths.get(filename));
    }
    private boolean isRoot(Path path) {
        if (!path.isAbsolute()) {
            path = path.toAbsolutePath();
        }
        return path.getParent() == null;
    }
    private void addList(Path path) {
        MyFile6699 file = new MyFile6699();
        file.setName(path.getFileName().toString());
        BasicFileAttributes attributes = null;
        try {
            attributes = Files.readAttributes(path, BasicFileAttributes.class);
            LocalDateTime time = attributes.lastModifiedTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();
            //将LocalDateTime按要求格式化为字符串
            String strTime = time.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
            file.setModifiedTime(strTime);
            if (Files.isDirectory(path)) {
                file.setSize("");
                file.setType("文件夹");
                nDir++;
            } else {
                nFile++;
                file.setSize((attributes.size() / 1024 + 1) + "KB");
                file.setType("");
            }
            list.add(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @FXML
    public void doubleClick(MouseEvent mouseEvent) throws IOException {
        if (mouseEvent.getClickCount() == 2) {
            //双击
            MyFile6699 file = tableFiles.getSelectionModel().getSelectedItem();
            if (file == null) return;//在标题上双击
            if ("文件夹".equals(file.getType())) {
                //定义要进入的下一级目录
                Path newDir = CuDir.resolve(file.getName());
                setCuDir(newDir);
            } else if ("..".equals(file.getName())) {
                //正确的从当前目录中读取上一级目录}
                Path newDir = CuDir.toRealPath().getParent();
                setCuDir(newDir);
            }
        }
    }
    private void setCuDir(Path dir) {
        CuDir = dir;
        tfDir.setText(dir.toString());
        nDir = 0;
        nFile = 0;
        list.clear();//清空ListView
        try (Stream<Path> ps = Files.list(dir)) {
            ps.forEach(this::addList);
        } catch (IOException e) {
            list.clear();
            e.printStackTrace();
            lblCount.setText(e.getMessage());
            return;
        }
        lblCount.setText("子目录：" + nDir + "文件：" + nFile);
        tableFiles.getSortOrder().clear();//清空排序
        tableFiles.getSortOrder().addAll(colType, colName);
        colType.setSortType(TableColumn.SortType.DESCENDING);
        colName.setSortType(TableColumn.SortType.ASCENDING);
        if (!isRoot(CuDir)) {
            MyFile6699 parent = new MyFile6699();
            parent.setName("..");
            list.add(0, parent);
        }
    }
}